package service

import (
	"io/ioutil"
	"gitee.com/man0sions/go-cron/common"
	"net/http"
	"strconv"
)

func handleJobSave(w http.ResponseWriter, r *http.Request) {
	//log.Println(r.Context().Value("__TEST_DATE__"))
	//log.Println(r.Context().Value("__LOG_ID__"))
	var (
		body   []byte
		err    error
		oldJob *common.Job
	)
	if body, err = ioutil.ReadAll(r.Body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return
	}
	if oldJob, err = common.GEtcd.JobSave(body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return
	}
	common.BuildResponse(w, common.CODE_OK, "", oldJob)
	return
}

func handleJobList(w http.ResponseWriter, r *http.Request) {
	list, err := common.GEtcd.JobList()
	if err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return
	}
	common.BuildResponse(w, common.CODE_OK, "", list)
	return

}

func handleJobDelete(w http.ResponseWriter, r *http.Request) {
	var (
		body   []byte
		err    error
		oldJob *common.Job
	)
	if body, err = ioutil.ReadAll(r.Body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return
	}
	if oldJob, err = common.GEtcd.JobDel(body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
	}
	common.BuildResponse(w, common.CODE_OK, "", oldJob)

	return

}

func handleJobKill(w http.ResponseWriter, r *http.Request) {
	var (
		body []byte
		err  error
	)
	if body, err = ioutil.ReadAll(r.Body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return
	}
	if err = common.GEtcd.JobKill(body); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
	}
	common.BuildResponse(w, common.CODE_OK, "", "")

	return

}

func handleWorkerList(w http.ResponseWriter, r *http.Request) {
	var (
		list []string
		err  error
	)

	if list, err = common.GEtcd.WorkList(); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
	}
	common.BuildResponse(w, common.CODE_OK, "", list)

	return

}

func handleLogs(w http.ResponseWriter, r *http.Request) {
	var (
		logRes      *common.LogRes
		err         error
		skip, limit int
	)
	name := r.FormValue("name")
	skipStr := r.FormValue("skip")
	limitStr := r.FormValue("limit")
	if skip, err = strconv.Atoi(skipStr); err != nil {
		skip = 0
	}
	if limit, err = strconv.Atoi(limitStr); err != nil {
		limit = 20
	}
	if logRes, err = common.GMongo.Logs(name, int64(limit), int64(skip)); err != nil {
		common.BuildResponse(w, common.CODE_ERR, err.Error(), "")
		return

	}
	common.BuildResponse(w, common.CODE_OK, "", logRes)

	return

}
func GetRoutes() (HandleMap map[string]http.HandlerFunc) {
	HandleMap = make(map[string]http.HandlerFunc)

	HandleMap["/job/save"] = handleJobSave
	HandleMap["/job/list"] = handleJobList
	HandleMap["/job/delete"] = handleJobDelete
	HandleMap["/job/kill"] = handleJobKill
	HandleMap["/job/logs"] = handleLogs
	HandleMap["/worker/list"] = handleWorkerList

	return
}
